from django.shortcuts import render

from django.http import JsonResponse
from django.core.paginator import Paginator
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from studentapp.models import Student
from studentapp.models import Class
from university_management_system.utils import is_empty


# 查询数据
@api_view(['get'])
def getdata(request):
    student_id = request.GET.get('student_id')
    name = request.GET.get('name')
    id_card = request.GET.get('id_card')
    page=request.GET.get('page')
    pagesize=request.GET.get('pageSize')
    where = {}
    if not is_empty(student_id):
        where['student_id__contains'] = student_id
    if not is_empty(name):
        where['name__contains'] = name
    if not is_empty(id_card):
        where['id_card__contains'] = id_card
    print(where)
    obj = Student.objects.filter(**where)

    p=Paginator(obj,pagesize)
    total=p.count
    pdata=p.page(page)
    print('***')
    print(p,total,pdata)
    data = []
    if len(obj) > 0:
        for i in pdata:
            data.append(
                {
                    "student_id": i.student_id,
                    "gender": i.gender,
                    "name": i.name,
                    "id_card": i.id_card,
                    "class_id": i._class.class_id,
                    "grade": i._class.grade,
                    "major": i._class.major.name,
                    "college": i._class.major.college.name,
                }
            )
    print(data)
    return JsonResponse({"code": 200, "message": "查询成功", "data": data,"total":total})

# 删除
@api_view(['delete'])
def handleDelete(request,id):
    obj=Student.objects.get(student_id=id)
    if not obj:
        return JsonResponse({"code": 1000, "message": "未找到数据"})
    obj.delete()

    return JsonResponse({"code": 200, "message": "删除成功"})

# 添加学生信息
@api_view(['post'])
def add_student(request):
    data=JSONParser().parse(request)
    data['photo']="1"
    print(data)
    Student.objects.create(**data)
    return JsonResponse({"code": 200, "message": "添加成功"})


# 添加学生信息
@api_view(['post'])
def updata_student(request):
    data=JSONParser().parse(request)
    data['photo']="1"
    print(data)
    id=data['student_id']
    Student.objects.filter(student_id=id).update(**data)
    return JsonResponse({"code": 200, "message": "修改成功"})


@api_view(['get'])
def get_select(request):
    obj=Class.objects.filter()
    data=[]
    for i in obj:
        data.append(
            {
                "lable":i.class_id,
                "value":i.class_id
            }
        )
    return JsonResponse({"code": 200, "message": "修改成功","data":data})

@api_view(['get'])
def get_putdata(request):
    student_id = request.GET.get('student_id')
    obj=Student.objects.filter(student_id=student_id).values().first()
    print('---')
    print(obj)
    return JsonResponse({"code": 200, "message": "查询成功", "data": obj})